package com.oceansoft.mobile.econsole.modules.jlapi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.constant.ConfigInfo;
import com.oceansoft.mobile.econsole.common.util.FtpBusiness;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.StringUtils;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.*;
import com.oceansoft.mobile.econsole.modules.jlapi.persistence.IJlApiInfoMapper;
import com.oceansoft.mobile.econsole.modules.jlapi.service.IJlApiService;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMember;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMemberMange;
import com.oceansoft.mobile.econsole.modules.member.persistence.IWtMemberMapper;
import com.oceansoft.mobile.econsole.modules.movecar.entity.MoveCar;
import com.oceansoft.mobile.econsole.modules.movecar.persistence.IMoveCarMapper;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * com.oceansoft.mobile.econsole.modules.jlapi.service.impl
 * Created by smc
 * date on 2016/3/10.
 * Email:sunmch@163.com
 * action标识符定义:
 * 实名认证：010101
 * 车辆违章查询：010102 list
 * 车辆查询:010103 list
 * 驾驶员查询：010104
 * 已决在押人员:010105 list
 * 重名查询：010106
 * 驾照查询：010107
 */
@Service
public class JlApiServiceImpl extends CacheBaseService implements IJlApiService {

    private static final Logger log = LoggerFactory.getLogger(JlApiServiceImpl.class);

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private IJlApiInfoMapper jlApiInfoMapper;

    @Resource
    private IMoveCarMapper moveCarMapper;

    @Resource
    private IWtMemberMapper wtMemberMapper;

    @Override
    public void insertInServiceInfo(InQueryServiceInfo inQueryServiceInfo) {
        jlApiInfoMapper.insertInServiceInfo(inQueryServiceInfo);
    }

    @Override
    public OutQueryServiceInfo queryOutServiceInfoByCondition(String action, String command) {
//        super.delCache("app:query:"+action+":"+command);
        OutQueryServiceInfo outQueryServiceInfo = getObject("app:query:"+action+":"+command,OutQueryServiceInfo.class);
        if(null == outQueryServiceInfo){
            List<OutQueryServiceInfo>  outQueryServiceInfos = jlApiInfoMapper.findOutServiceInfoByCondition(action,command);
            if(null != outQueryServiceInfos && outQueryServiceInfos.size()>0){
                outQueryServiceInfo = outQueryServiceInfos.get(0);
                cache("app:query:"+action+":"+command,outQueryServiceInfo,24*3600);
                cache("app:query:"+action+":"+outQueryServiceInfo.getSn(),outQueryServiceInfo,24*3600);
            }
        }

        return outQueryServiceInfo;
    }

    @Override
    public List<OutQueryServiceInfo2> queryOutServiceInfoByCondition2(String action, String command) {

        List<OutQueryServiceInfo2> outQueryServiceInfos= jlApiInfoMapper.findOutServiceInfoByCondition2(action, command);

        return outQueryServiceInfos;
    }

    @Override
    public OutQueryServiceInfo queryOutServiceInfoByCondition3(String action, String command) {
        OutQueryServiceInfo outQueryServiceInfo= new OutQueryServiceInfo();
        List<OutQueryServiceInfo> outQueryServiceInfos= jlApiInfoMapper.findOutServiceInfoByCondition3(action, command);
        if(null != outQueryServiceInfos && outQueryServiceInfos.size()>0){
            outQueryServiceInfo = outQueryServiceInfos.get(0);
        }
        return outQueryServiceInfo;
    }

    @Override
    public OutQueryServiceInfo queryOutServiceInfo(String action, String command,String sn) {

        List<OutQueryServiceInfo>  outQueryServiceInfos = jlApiInfoMapper.queryListOutServiceInfo(sn);
        OutQueryServiceInfo outQueryServiceInfo = null;
        if(null != outQueryServiceInfos && outQueryServiceInfos.size()>0){
            outQueryServiceInfo = outQueryServiceInfos.get(0);
            cache("app:query:"+action+":"+command,outQueryServiceInfo,24*3600);
            cache("app:query:"+action+":"+sn,outQueryServiceInfo,24*3600);
        }
        return outQueryServiceInfo;
    }

    @Override
    public List<OutQueryServiceInfo2> queryOutServiceInfo2( String sn) {
        List<OutQueryServiceInfo2> outQueryServiceInfos = jlApiInfoMapper.queryListOutServiceInfo2(sn);
        return outQueryServiceInfos;
    }

    @Override
    public InQueryServiceInfo findInQueryBySN(String sn) {
        return jlApiInfoMapper.findInQueryBySN(sn);
    }

    @Override
    public void doExecute(InQueryServiceInfo inQueryServiceInfo, ApiMessage message) {
        threadPoolTaskExecutor.execute(new InThead(inQueryServiceInfo,message));
    }

    @Override
    public List<OffenseVehicleInfo> doExecutes(InQueryServiceInfo inQueryServiceInfo)  {
        List<OffenseVehicleInfo> list = new ArrayList<>();
        String action = inQueryServiceInfo.getAction();
        String command = inQueryServiceInfo.getCommand();

        // 1- 查询已经存在OUT_ATT表数据
        List<OutQueryServiceInfo2> outQueryServiceInfo = this.queryOutServiceInfoByCondition2(action, command);

        if (outQueryServiceInfo.isEmpty()) {
            log.info("++++++++++++++ 无缓存数据 ++++++++++++++++++++");

            // 2-插入IN表数据
            this.insertInServiceInfo(inQueryServiceInfo);

            try {
                Thread.sleep(20000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            log.info("+++++++++++++ 开始查询OUT数据 ++++++++++++++++++");
            for (int searchCount = 0; searchCount <10; searchCount++) {

                log.info("++++++++++++++ 查询OUT 表次数++++++++++++++++++++ " + searchCount );

                // 3- 查询OUT-ATT表数据
                outQueryServiceInfo = this.queryOutServiceInfoByCondition2(action, command);
                if (!outQueryServiceInfo.isEmpty()) {
                    // 查询结果获取成功且成功查询出所需信息，退出轮
                    break;
                }
                try {
                    if(searchCount!=9) {
                        Thread.sleep(10000L);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

        if (!outQueryServiceInfo.isEmpty()) {
            log.info("#### ++++++++++++++ 查询数据成功++++++++++++++++++++ ");
            for (OutQueryServiceInfo2 outQueryServiceInfo2 : outQueryServiceInfo) {
                if(!Strings.isNullOrEmpty(outQueryServiceInfo2.getRes()) && Objects.equals("000", outQueryServiceInfo2.getCode())) {
                    OffenseVehicleInfo OffenseVehicleInfo = JSONObject.parseObject(outQueryServiceInfo2.getRes(), OffenseVehicleInfo.class);
                    list.add(OffenseVehicleInfo);
                }
            }
            log.info("+++++++++++++++数据正确返回+++++++++++++++++++++++++");
        }else{
            log.error("查询标识符:{},查询条件：{}，没有查询到数据", action, command);
            return Collections.emptyList();
        }

        return list;
    }


    @Override
    public Vehicle doExecutes3(InQueryServiceInfo inQueryServiceInfo) throws ExecutionException, InterruptedException {

        Vehicle vehicle = new Vehicle();
        OutQueryServiceInfo  outQueryServiceInfo = queryOutServiceInfoByCondition3(inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());    //上传已经存在数据

        if (null==outQueryServiceInfo||!("".equals(outQueryServiceInfo))) {
            System.out.println("无缓存");
                insertInServiceInfo(inQueryServiceInfo);
                Thread.sleep(20000);
                log.debug("开始查询放回数据");
                int searchCount = 0;
                for (searchCount = 0; searchCount < 20; searchCount++) {
                    //                        outQueryServiceInfo = queryOutServiceInfo(this.inQueryServiceInfo.getAction(), this.inQueryServiceInfo.getCommand(), this.inQueryServiceInfo.getSn());
                    outQueryServiceInfo = queryOutServiceInfoByCondition3(inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());
                    if (null != outQueryServiceInfo&&null!=outQueryServiceInfo.getRes()) {
                        // 查询结果获取成功且成功查询出所需信息，退出轮
                        break;
                    }
                    Thread.sleep(5000);
                }
        }
        if(null!=outQueryServiceInfo.getRes()&&!("".equals(outQueryServiceInfo.getRes()))&&"000".equals(outQueryServiceInfo.getCode())){
            vehicle = JSONObject.parseObject(outQueryServiceInfo.getRes().toString(), Vehicle.class);
        }else
        {
            vehicle.setZt("-1");
        }
        return vehicle;
    }
    @Override
    public DriverLicenseInfo doExecutes2(InQueryServiceInfo inQueryServiceInfo) throws ExecutionException, InterruptedException {

        DriverLicenseInfo driverLicenseInfo=new DriverLicenseInfo();

        OutQueryServiceInfo  outQueryServiceInfo = queryOutServiceInfoByCondition3(inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());    //上传已经存在数据

        if (null==outQueryServiceInfo||!("".equals(outQueryServiceInfo))) {
            System.out.println("无缓存");
            try {
                insertInServiceInfo(inQueryServiceInfo);
                Thread.sleep(20000);
                log.debug("开始查询放回数据");
                int searchCount = 0;
                for (searchCount = 0; searchCount < 20; searchCount++) {
                    //                        outQueryServiceInfo = queryOutServiceInfo(this.inQueryServiceInfo.getAction(), this.inQueryServiceInfo.getCommand(), this.inQueryServiceInfo.getSn());
                    outQueryServiceInfo = queryOutServiceInfoByCondition3(inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());
                    if (null != outQueryServiceInfo&&null!=outQueryServiceInfo.getRes()) {
                        // 查询结果获取成功且成功查询出所需信息，退出轮
                        break;
                    }
                    Thread.sleep(5000);
                }

            } catch (Exception ex) {
                log.error("查询接口失败,失败信息:", ex);
            }
        }
                if(null!=outQueryServiceInfo.getRes()&&!("".equals(outQueryServiceInfo.getRes()))&&"000".equals(outQueryServiceInfo.getCode()) ){
                    driverLicenseInfo=JSONObject.parseObject(outQueryServiceInfo.getRes().toString(), DriverLicenseInfo.class);
                }else{
                    driverLicenseInfo.setJdcjszljjf("-1");
                }

        return driverLicenseInfo;
    }

    @Override
    public Boolean doExecute(InQueryServiceInfo inQueryServiceInfo) throws ExecutionException, InterruptedException {
        FutureTask<OutQueryServiceInfo> futureTask = new FutureTask<>(new InTheads2(inQueryServiceInfo));
        threadPoolTaskExecutor.execute(futureTask);
        System.out.println("请求完毕");
        Thread.sleep(10000);
        OutQueryServiceInfo outQueryServiceInfo = futureTask.get();
        for(int i=0;i<5;i++){
            if(null==outQueryServiceInfo||"".equals(outQueryServiceInfo)){
                outQueryServiceInfo = futureTask.get();
                Thread.sleep(2000);
            }else{
                outQueryServiceInfo = futureTask.get();
                break;
            }
        }
        if("000".equals(outQueryServiceInfo.getCode())){
            return true;
        }
      return false;

    }

    @Override
    public void doMoveCarExecute(InQueryServiceInfo inQueryServiceInfo, ApiMessage message, MoveCar moveCar) {
        threadPoolTaskExecutor.execute(new InMoveCarThead(inQueryServiceInfo, message, moveCar));
    }

    @Override
    public void doSmrz(InQueryServiceInfo inQueryServiceInfo){
        threadPoolTaskExecutor.execute(new SmrzThread(inQueryServiceInfo));
    }


    @Override
    public void doFtpUploadFile(ConfigInfo configInfo, String fileName, String filePath, InputStream in) {
        threadPoolTaskExecutor.execute(new FtpUploadFileThread(configInfo, fileName, filePath, in));
    }


    private class InTheads2 implements Callable<OutQueryServiceInfo> {

        private InQueryServiceInfo inQueryServiceInfo;
        private String returnStr = "查询失败";
        String conditionStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        public InTheads2(InQueryServiceInfo inQueryServiceInfo) {
            this.inQueryServiceInfo = inQueryServiceInfo;
        }

        @Override
        public OutQueryServiceInfo call() {
            OutQueryServiceInfo  outQueryServiceInfo = queryOutServiceInfoByCondition3(inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());    //上传已经存在数据
            if (null==outQueryServiceInfo||!("".equals(outQueryServiceInfo))) {
                System.out.println("无缓存");
                try {
                    insertInServiceInfo(this.inQueryServiceInfo);
                    Thread.sleep(10000);
                    log.debug("开始查询放回数据");
                    int searchCount = 0;
                    for (searchCount = 0; searchCount < 9; searchCount++) {
//                        outQueryServiceInfo = queryOutServiceInfo(this.inQueryServiceInfo.getAction(), this.inQueryServiceInfo.getCommand(), this.inQueryServiceInfo.getSn());
                        outQueryServiceInfo = queryOutServiceInfoByCondition3(inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());
                        if (null != outQueryServiceInfo) {
                            // 查询结果获取成功且成功查询出所需信息，退出轮
                            break;
                        }
                        if (null != outQueryServiceInfo) {
                            if (outQueryServiceInfo.getCode() == "111111") {
                                returnStr = "您输入的发动机号与车牌号不匹配，请确认后再查询！";
                                break;
                            }
                            // 查询结果获取成功但未查询出所需信息，退出轮训
                            if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_002)) {
                                returnStr = "目前无违章记录！";
                            } else {
                                returnStr = "没有查询到相应的数据";
                            }

                            break;
                        }
                        Thread.sleep(5000);
                    }
                    if (searchCount >= 9) {
                        log.error("查询标识符:{},查询条件：{}，没有查询到数据", inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());
                            return null;
                    }
                } catch (Exception ex) {
                    log.error("查询接口失败,失败信息:", ex);
                }

            }
            try {
                if (null==outQueryServiceInfo||!("".equals(outQueryServiceInfo))) {
                    return outQueryServiceInfo;


                }

            } catch (Exception e) {
                log.error("返回数据失败信息:", e);
            }
            return outQueryServiceInfo;


        }
    }





    private class InThead implements Runnable {

        private InQueryServiceInfo inQueryServiceInfo;
        private ApiMessage message;
        private String returnStr = "查询失败";
        String conditionStr = "";
        SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        public  InThead(InQueryServiceInfo inQueryServiceInfo,ApiMessage message){
            this.inQueryServiceInfo = inQueryServiceInfo;
            this.message = message;
        }
        @Override
        public void run() {
            OutQueryServiceInfo outQueryServiceInfo = queryOutServiceInfoByCondition(inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());    //上传已经存在数据

            if (null == outQueryServiceInfo) {
                try {
                    insertInServiceInfo(this.inQueryServiceInfo);
                    Thread.sleep(10000L);
                    log.debug("开始查询放回数据");
                    int searchCount = 0;
                    for (searchCount = 0; searchCount < 9; searchCount++) {
                        outQueryServiceInfo = queryOutServiceInfo(this.inQueryServiceInfo.getAction(), this.inQueryServiceInfo.getCommand(), inQueryServiceInfo.getSn());
                        if (null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())) {
                            // 查询结果获取成功且成功查询出所需信息，退出轮训
                            break;
                        }
                        if (null != outQueryServiceInfo && StringUtils.isBlank(outQueryServiceInfo.getRes())) {
                            if (outQueryServiceInfo.getCode() == "111111") {
                                returnStr = "您输入的发动机号与车牌号不匹配，请确认后再查询！";
                                break;
                            }
                            // 查询结果获取成功但未查询出所需信息，退出轮训
                            if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_002)) {
                                returnStr = "目前无违章记录！";
                            } else {
                                returnStr = "没有查询到相应的数据";
                            }

                            break;
                        }
                        Thread.sleep(10000L);
                    }
                    if (searchCount >= 9) {
                        log.error("查询标识符:{},查询条件：{}，没有查询到数据", inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());

                        if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_001)) {
                            PermanentPopulationSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), PermanentPopulationSearchCondition.class);
                            conditionStr = "身份证核查:" + condition.getGmsfhm();
                        } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_002)) {
                            OffenseVehicleSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), OffenseVehicleSearchCondition.class);
                            conditionStr = "机动车违法查询:车牌号：" + condition.getJdchphm();
                        } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_003)) {
                            VehicleSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), VehicleSearchCondition.class);
                            conditionStr = "车牌号核查：" + condition.getJdchphm();
                        } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_004)) {

                        } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_005)) {

                        } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_006)) {
                            NameSakeSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), NameSakeSearchCondition.class);
                            conditionStr = "重名查询:" + condition.getXm();
                        } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_007)) {
                            DriverLicenseSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), DriverLicenseSearchCondition.class);
                            conditionStr = "驾驶证记分查询:驾驶证号：" + condition.getJtglywdxsfzhm().substring(0, 6) + "***********" + condition.getJtglywdxsfzhm().substring(17);
                        }
                        if (message.getChannel().equals(PushChannel.APP)) {
                            AppMessage appMessage = (AppMessage) message;
                            appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                            appMessage.setTitle(returnStr);
                            appMessage.setContent(conditionStr);
                            appMessage.setUrl("");
                            HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);

                        } else if (message.getChannel().equals(PushChannel.SMS)) {
                            SMSMessage smsMessage = (SMSMessage) message;

                        } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                            WechatMessage wechatMessage = (WechatMessage) message;
                            wechatMessage.setParams(new HashMap<String, String[]>() {{
                                put("first", new String[]{"消息通知", "#173177"});
                                put("keyword1", new String[]{conditionStr, "#173177"});
                                put("keyword2", new String[]{returnStr, "#173177"});
                                put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                                put("remark", new String[]{"如果提示查询失败，请重新查询你需要的信息", "#173177"});
                            }});
                            String resp = HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);
                            log.error("推送消息返回:", resp);
                        }
                    }
                } catch (Exception ex) {
                    log.error("查询接口失败,失败信息:", ex);
                }

            }

            if (null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())) {
                try {
                    if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_001)) {
                        //实名认证
                        PermanentPopulationSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), PermanentPopulationSearchCondition.class);
                        RealNameAuthInfo realNameAuthInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), RealNameAuthInfo.class);
                        if (message.getChannel().equals(PushChannel.APP)) {
                            AppMessage appMessage = (AppMessage) message;
                            appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                            appMessage.setTitle("身份证核查");
                            appMessage.setContent("姓名：" + realNameAuthInfo.getXm() + "\t\t单位" + realNameAuthInfo.getSjgsdwmc() + "\t\t派出所" + realNameAuthInfo.getSspcs());
                            appMessage.setUrl("");
                            Map<String, String> map = new HashMap<>();
                            map.put("sn", outQueryServiceInfo.getSn());
                            map.put("action", outQueryServiceInfo.getAction());
                            appMessage.setExtra(map);
                            HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);
                        } else if (message.getChannel().equals(PushChannel.SMS)) {
                            SMSMessage smsMessage = (SMSMessage) message;
                        } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                            WechatMessage wechatMessage = (WechatMessage) message;
                            wechatMessage.setParams(new HashMap<String, String[]>() {{
                                put("first", new String[]{"消息通知", "#173177"});
                                put("keyword1", new String[]{"身份证核查:" + condition.getGmsfhm(), "#173177"});
                                if (realNameAuthInfo.getExist().equals("Y")) {
                                    put("keyword2", new String[]{"核查结果：\n" + "姓名：" + realNameAuthInfo.getXm() + "\t\t单位" + realNameAuthInfo.getSjgsdwmc() + "\t\t派出所" + realNameAuthInfo.getSspcs(), "#173177"});
                                } else {
                                    put("keyword2", new String[]{"核查结果：身份证号不存在" + "", "#173177"});
                                }
                                put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                                put("remark", new String[]{"如果提示查询失败，请重新查询你需要的信息", "#173177"});
                            }});
                            HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);
                        }

                    } else if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_002)) {
                        // 车辆违章查询
                        OffenseVehicleSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), OffenseVehicleSearchCondition.class);
                        List<OffenseVehicleInfo> list = JSONArray.parseArray(outQueryServiceInfo.getRes(), OffenseVehicleInfo.class);
                        if (message.getChannel().equals(PushChannel.APP)) {
                            AppMessage appMessage = (AppMessage) message;
                            appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                            appMessage.setTitle("机动车违法");
                            appMessage.setContent("违法记录详细列表");
                            appMessage.setUrl("");
                            Map<String, String> map = new HashMap<>();
                            map.put("sn", outQueryServiceInfo.getSn());
                            map.put("action", outQueryServiceInfo.getAction());
                            appMessage.setExtra(map);
                            HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);

                        } else if (message.getChannel().equals(PushChannel.SMS)) {
                            SMSMessage smsMessage = (SMSMessage) message;

                        } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                            WechatMessage wechatMessage = (WechatMessage) message;
                            wechatMessage.setUrl("https://app.cyga.gov.cn/econsole/api/query/result/gain?sn="
                                    + outQueryServiceInfo.getSn() + "&action=" + outQueryServiceInfo.getAction() + "");
                            wechatMessage.setParams(new HashMap<String, String[]>() {{
                                put("first", new String[]{"消息通知", "#173177"});
                                put("keyword1", new String[]{"机动车违法查询:车牌号：" + condition.getJdchphm(), "#173177"});
                                put("keyword2", new String[]{"机动车存在未处理违章，请点击详情查看", "#173177"});
                                put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                                put("remark", new String[]{"如果提示查询失败，请重新查询你需要的信息", "#173177"});
                            }});
                            HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);

                        }

                    } else if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_003)) {
                        // 车辆查询
                        VehicleSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), VehicleSearchCondition.class);
                        List<VehicleItem> list = JSONArray.parseArray(outQueryServiceInfo.getRes(), VehicleItem.class);
                        StringBuffer keywordsStr = new StringBuffer();
                        for (int i = 0; i < list.size(); i++) {
                            VehicleItem e = list.get(i);
                            int index = i + 1;
                            keywordsStr.append(index + "、车辆类型：" + e.getClly() + "\t\t品牌名称：" + e.getClpp1() + "\t\t出厂日期：" + e.getCcrq() + "\n");
                        }
                        if (message.getChannel().equals(PushChannel.APP)) {
                            AppMessage appMessage = (AppMessage) message;
                            appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                            appMessage.setTitle("车牌号核查");
                            appMessage.setContent("车辆信息列表请点击详情");
                            appMessage.setUrl("");
                            Map<String, String> map = new HashMap<>();
                            map.put("sn", outQueryServiceInfo.getSn());
                            map.put("action", outQueryServiceInfo.getAction());
                            appMessage.setExtra(map);
                            HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);

                        } else if (message.getChannel().equals(PushChannel.SMS)) {
                            SMSMessage smsMessage = (SMSMessage) message;

                        } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                            WechatMessage wechatMessage = (WechatMessage) message;
                            wechatMessage.setParams(new HashMap<String, String[]>() {{
                                put("first", new String[]{"消息通知", "#173177"});
                                put("keyword1", new String[]{"车牌号核查：" + condition.getJdchphm(), "#173177"});
                                put("keyword2", new String[]{"核查结果：\n" + keywordsStr.toString(), "#173177"});
                                put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                                put("remark", new String[]{"如果提示查询失败，请重新查询你需要的信息", "#173177"});
                            }});
                            HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);
                        }

                    } else if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_004)) {
                        // 驾驶员查询

                    } else if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_005)) {
                        // 已决在押人员

                    } else if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_006)) {
                        // 重名查询
                        NameSakeSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), NameSakeSearchCondition.class);
                        NameSakeInfo nameSakeInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), NameSakeInfo.class);
                        if (message.getChannel().equals(PushChannel.APP)) {
                            AppMessage appMessage = (AppMessage) message;
                            appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                            appMessage.setTitle("重名查询");
                            appMessage.setContent("在本省范围内，与您输入的姓名重名的人数为" + nameSakeInfo.getCount() + "人");
                            appMessage.setUrl("");
                            Map<String, String> map = new HashMap<>();
                            map.put("sn", outQueryServiceInfo.getSn());
                            map.put("action", outQueryServiceInfo.getAction());
                            appMessage.setExtra(map);
                            HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);

                        } else if (message.getChannel().equals(PushChannel.SMS)) {
                            SMSMessage smsMessage = (SMSMessage) message;

                        } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                            WechatMessage wechatMessage = (WechatMessage) message;
                            wechatMessage.setUrl("https://app.cyga.gov.cn/econsole/api/query/result/gain?sn="
                                    + outQueryServiceInfo.getSn() + "&action=" + outQueryServiceInfo.getAction() + "");
                            wechatMessage.setParams(new HashMap<String, String[]>() {{
                                put("first", new String[]{"消息通知", "#173177"});
                                put("keyword1", new String[]{"重名查询:" + condition.getXm(), "#173177"});
                                put("keyword2", new String[]{"在本省范围内，与您输入的姓名重名的人数为" + nameSakeInfo.getCount() + "人", "#173177"});
                                put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                                put("remark", new String[]{"如果提示查询失败，请重新查询你需要的信息", "#173177"});
                            }});
                            HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);
                        }

                    } else if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_007)) {
                        // 驾照查询
                        DriverLicenseSearchCondition condition = JSONObject.parseObject(outQueryServiceInfo.getRes(), DriverLicenseSearchCondition.class);
                        DriverLicenseInfo driverLicenseInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), DriverLicenseInfo.class);
                        StringBuffer keywordStr = new StringBuffer();
                        keywordStr.append("您的驾驶证累计记分为" + driverLicenseInfo.getJdcjszljjf() + "分");
                        if (message.getChannel().equals(PushChannel.APP)) {
                            AppMessage appMessage = (AppMessage) message;
                            appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                            appMessage.setTitle("驾驶证记分");
                            appMessage.setContent("驾驶证记分信息请点击详情");
                            appMessage.setUrl("");
                            Map<String, String> map = new HashMap<>();
                            map.put("sn", outQueryServiceInfo.getSn());
                            map.put("action", outQueryServiceInfo.getAction());
                            appMessage.setExtra(map);
                            HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);

                        } else if (message.getChannel().equals(PushChannel.SMS)) {
                            SMSMessage smsMessage = (SMSMessage) message;

                        } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                            WechatMessage wechatMessage = (WechatMessage) message;
                            wechatMessage.setParams(new HashMap<String, String[]>() {{
                                put("first", new String[]{"消息通知", "#173177"});
                                put("keyword1", new String[]{"驾驶证记分查询:\n驾驶证号：" + condition.getJtglywdxsfzhm().substring(0, 6) + "***********" + condition.getJtglywdxsfzhm().substring(17), "#173177"});
                                put("keyword2", new String[]{"驾驶证信息：\n" + keywordStr, "#173177"});
                                put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                                put("remark", new String[]{"如果提示查询失败，请重新查询你需要的信息", "#173177"});
                            }});
                            HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);
                        }


                    }
                } catch (Exception e) {
                    log.error("消息中心推送失败,失败信息:", e);
                }

            } else if (null != outQueryServiceInfo && StringUtils.isBlank(outQueryServiceInfo.getRes())) {
                log.error("查询标识符:{},查询条件：{}，没有查询到数据", inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());

                if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_002)) {
                    if (outQueryServiceInfo.getCode() == "111111") {
                        returnStr = "您输入的发动机号与车牌号不匹配，请确认后再查询！";
                    } else {
                        returnStr = "目前无违章记录！";
                    }
                } else {
                    returnStr = "没有查询到相应的数据";
                }

                if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_001)) {
                    PermanentPopulationSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), PermanentPopulationSearchCondition.class);
                    conditionStr = "身份证核查:" + condition.getGmsfhm();
                } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_002)) {
                    OffenseVehicleSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), OffenseVehicleSearchCondition.class);
                    conditionStr = "机动车违法查询:车牌号：" + condition.getJdchphm();
                } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_003)) {
                    VehicleSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), VehicleSearchCondition.class);
                    conditionStr = "车牌号核查：" + condition.getJdchphm();
                } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_004)) {

                } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_005)) {

                } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_006)) {
                    NameSakeSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), NameSakeSearchCondition.class);
                    conditionStr = "重名查询:" + condition.getXm();
                } else if (inQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_007)) {
                    DriverLicenseSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), DriverLicenseSearchCondition.class);
                    conditionStr = "驾驶证记分查询:驾驶证号：" + condition.getJtglywdxsfzhm().substring(0, 6) + "***********" + condition.getJtglywdxsfzhm().substring(17);
                }
                if (message.getChannel().equals(PushChannel.APP)) {
                    AppMessage appMessage = (AppMessage) message;
                    appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                    appMessage.setTitle(returnStr);
                    appMessage.setContent(conditionStr);
                    appMessage.setUrl("");
                    HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);

                } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                    WechatMessage wechatMessage = (WechatMessage) message;
                    wechatMessage.setParams(new HashMap<String, String[]>() {{
                        put("first", new String[]{"消息通知", "#173177"});
                        put("keyword1", new String[]{conditionStr, "#173177"});
                        put("keyword2", new String[]{returnStr, "#173177"});
                        put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                        put("remark", new String[]{"如果提示查询失败，请重新查询你需要的信息", "#173177"});
                    }});
                    String resp = HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);
                    log.error("推送消息返回:", resp);
                }
            }
        }
    }

    private class InMoveCarThead implements Runnable {
        private InQueryServiceInfo inQueryServiceInfo;
        private ApiMessage message;
        private MoveCar moveCar;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        public InMoveCarThead(InQueryServiceInfo inQueryServiceInfo, ApiMessage message, MoveCar moveCar) {
            this.inQueryServiceInfo = inQueryServiceInfo;
            this.message = message;
            this.moveCar = moveCar;
        }

        @Override
        public void run() {
            OutQueryServiceInfo outQueryServiceInfo = getObject("APP:QUERY:" + inQueryServiceInfo.getAction() + ":" + inQueryServiceInfo.getCommand(), OutQueryServiceInfo.class);    //上传已经存在数据
            if (null == outQueryServiceInfo) {
                try {
                    insertInServiceInfo(this.inQueryServiceInfo);
                    Thread.sleep(10000L);
                    log.debug("开始查询放回堵路移车车主信息数据");
                    int searchCount = 0;
                    for (searchCount = 0; searchCount < 9; searchCount++) {
                        outQueryServiceInfo = queryOutServiceInfo(this.inQueryServiceInfo.getAction(), this.inQueryServiceInfo.getCommand(), inQueryServiceInfo.getSn());
                        if (null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())) {
                            // 查询结果获取成功且成功查询出所需信息，退出轮训
                            break;
                        }
                        if (null != outQueryServiceInfo && StringUtils.isBlank(outQueryServiceInfo.getRes())) {
                            // 查询结果获取成功但未查询出所需信息，退出轮训
                            searchCount = 9;
                            break;
                        }
                        Thread.sleep(10000L);
                    }
                    if (searchCount >= 9) {
                        log.error("查询标识符:{},查询条件：{}，没有查询到堵路移车车主数据", inQueryServiceInfo.getAction(), inQueryServiceInfo.getCommand());
                        if (message.getChannel().equals(PushChannel.APP)) {
                            AppMessage appMessage = (AppMessage) message;
                            appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                            appMessage.setTitle("查询失败");
                            appMessage.setContent("堵路车主信息获取失败");
                            appMessage.setUrl("");
                            HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);

                        } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                            VehicleSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), VehicleSearchCondition.class);
                            WechatMessage wechatMessage = (WechatMessage) message;
                            wechatMessage.setParams(new HashMap<String, String[]>() {{
                                put("first", new String[]{"消息通知", "#173177"});
                                put("keyword1", new String[]{"堵路车牌号:辽" + condition.getJdchphm(), "#173177"});
                                put("keyword2", new String[]{"抱歉，未查到该车主的信息，请核对车辆信息或直接拨打报警电话110!", "#173177"});
                                put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                                put("remark", new String[]{"如果提示查询失败，请重新提交堵路移车信息", "#173177"});
                            }});
                            HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);
                        }
                    }
                } catch (Exception ex) {
                    log.error("查询接口失败,失败信息:", ex);
                }

            }

            if (null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())) {
                try {
                    if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_003)) {
                        // 车辆查询
                        VehicleSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), VehicleSearchCondition.class);
                        List<VehicleItem> list = JSONArray.parseArray(outQueryServiceInfo.getRes(), VehicleItem.class);

                        // 更新车主信息
                        if (null != list && 0 < list.size()) {
                            VehicleItem vehicleItem = list.get(0);
                            moveCar.setCarOwner(vehicleItem.getJdc_syr());
                            if (StringUtils.isNotBlank(vehicleItem.getSjhm())) {
                                moveCar.setOwnerMobile(vehicleItem.getSjhm());
                            } else {
                                moveCar.setOwnerMobile(vehicleItem.getLxdh());
                            }
                            moveCar.setOwnerIdCard(vehicleItem.getJtglywdxsfzmhm());
                            moveCar.setCarInfo(vehicleItem.getClly() + "," + vehicleItem.getClpp1());

                            // 更新车主信息
                            moveCarMapper.updateCarOwnerInfo(moveCar);
                            // 发送短信给堵路车主
                            SMSMessage smsMessage = new SMSMessage();
                            smsMessage.setReceiver(moveCar.getOwnerMobile());
                            smsMessage.setContent("您的车辆【" + moveCar.getCarNo() + "】在【" + moveCar.getAddress() + "】阻塞交通，影响他人通行，请立即处理!");
                            String resp = HttpClientUtil.doPostString(configInfo.getSmsSendUrl(), smsMessage);

                        }

                        if (message.getChannel().equals(PushChannel.APP)) {
                            AppMessage appMessage = (AppMessage) message;
                            appMessage.setMsgType(AppMessage.MessageType.QUERY_SERVICE);
                            appMessage.setTitle("堵路移车");
                            appMessage.setContent("已成功短信通知[辽" + condition.getJdchphm() + "]的车主，请耐心等待");
                            appMessage.setUrl("");
                            appMessage.setHphm(condition.getJdchphm());
                            HttpClientUtil.doPostString(configInfo.getAppSendUrl(), appMessage);

                        } else if (message.getChannel().equals(PushChannel.WECHAT)) {
                            WechatMessage wechatMessage = (WechatMessage) message;
                            wechatMessage.setParams(new HashMap<String, String[]>() {{
                                put("first", new String[]{"消息通知", "#173177"});
                                put("keyword1", new String[]{"堵路车牌号：" + condition.getJdchphm(), "#173177"});
                                put("keyword2", new String[]{"已成功短信通知堵路车车主，请耐心等待", "#173177"});
                                put("keyword3", new String[]{sdf.format(new Date()), "#173177"});
                                put("remark", new String[]{"如果提示查询失败，请重新提交堵路移车信息", "#173177"});
                            }});
                            HttpClientUtil.doPostString(configInfo.getWechatSendUrl(), wechatMessage);
                        }

                    }
                } catch (Exception e) {
                    log.error("消息中心推送失败,失败信息:", e);
                }
            }
        }
    }

    private class SmrzThread implements Runnable {
        private InQueryServiceInfo inQueryServiceInfo;
        private String returnStr = "查询失败";

        public SmrzThread(InQueryServiceInfo inQueryServiceInfo) {
            this.inQueryServiceInfo = inQueryServiceInfo;
        }

        @Override
        public void run() {
            OutQueryServiceInfo outQueryServiceInfo = getObject("APP:QUERY:" + inQueryServiceInfo.getAction() + ":" + inQueryServiceInfo.getCommand(), OutQueryServiceInfo.class);
            if (null == outQueryServiceInfo) {
                try {
                    insertInServiceInfo(this.inQueryServiceInfo);
                    Thread.sleep(10000L);
                    int searchCount = 0;
                    for (searchCount = 0; searchCount < 9; searchCount++) {
                        outQueryServiceInfo = queryOutServiceInfo(this.inQueryServiceInfo.getAction(), this.inQueryServiceInfo.getCommand(), inQueryServiceInfo.getSn());
                        if (null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())) {
                            // 查询结果获取成功且成功查询出所需信息，退出轮训
                            break;
                        }
                        if (null != outQueryServiceInfo && StringUtils.isBlank(outQueryServiceInfo.getRes())) {
                            // 查询结果获取成功但未查询出所需信息，退出轮训
                            returnStr = "没有查询到相应的数据";
                            searchCount = 9;
                            break;
                        }
                        Thread.sleep(10000L);
                    }

                    // 认证表插入未认证
                    String rzxx = inQueryServiceInfo.getCommand();
                    PermanentPopulationSearchCondition pp = JSONObject.parseObject(rzxx, PermanentPopulationSearchCondition.class);
                    /*if(searchCount>=9){
                        WtMemberMange wtMemberMange = new WtMemberMange();
                        wtMemberMange.setGuid(pp.getGuid());
                        // 认证中
                        wtMemberMange.setIdentityStatus(2);
                        wtMemberMange.setIsCheck(0);
                        wtMemberMange.setIsEnabled(0);
                        // 删除认证信息表数据
                        wtMemberMapper.delWtMemberManage(wtMemberMange.getGuid());
                        // 认证信息表插入数据
                        wtMemberMapper.insertWtMemberMange(wtMemberMange);
                    }*/
                    // 更新认证时间
                    WtMember wtMember = new WtMember();
                    wtMember.setGuid(pp.getUserguid());
                    wtMember.setCertificate("0");
                    wtMember.setCsny(new Date());
                    wtMemberMapper.updateWtMemberByUserGuid(wtMember);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())) {
                WtMemberMange wtMemberMange = new WtMemberMange();


                if (outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_001)) {
                    //实名认证
                    PermanentPopulationSearchCondition condition = JSONObject.parseObject(inQueryServiceInfo.getCommand(), PermanentPopulationSearchCondition.class);
                    RealNameAuthInfo realNameAuthInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), RealNameAuthInfo.class);
                    String rzxx = inQueryServiceInfo.getCommand();
                    PermanentPopulationSearchCondition pp = JSONObject.parseObject(rzxx, PermanentPopulationSearchCondition.class);
                    String xm = realNameAuthInfo.getXm();
                    String sfzh = realNameAuthInfo.getSfzh();
                    wtMemberMange.setGuid(pp.getUserguid());
                    if (rzxx.indexOf(xm) >= 0 && rzxx.indexOf(sfzh) >= 0) {
                        // 认证成功
                        wtMemberMange.setIdentityStatus(1);
                    } else {
                        wtMemberMange.setIdentityStatus(-9);
                    }

                    //wtMemberMapper.getWtMemberMange(wtMemberMange.getGuid());
                    // 删除认证信息表数据
                    //wtMemberMapper.delWtMemberManage(wtMemberMange.getGuid());
                    // 认证信息表插入数据
                    //wtMemberMapper.insertWtMemberMange(wtMemberMange);

                    // 更新认证时间
                    WtMember wtMember = new WtMember();
                    wtMember.setGuid(wtMemberMange.getGuid());
                    wtMember.setCertificate("0");
                    wtMember.setCsny(new Date());
                    wtMemberMapper.updateWtMemberByUserGuid(wtMember);


                }
            }
        }
    }

    private class FtpUploadFileThread implements Runnable {

        private ConfigInfo configInfo;
        private String fileName;
        private String filePath;
        private InputStream in;

        public FtpUploadFileThread(ConfigInfo configInfo, String fileName, String filePath, InputStream in) {
            this.configInfo = configInfo;
            this.fileName = fileName;
            this.filePath = filePath;
            this.in = in;
        }

        @Override
        public void run() {
            try {
                log.info("*************************FtpUploadFileThread线程启动上传文件************************");
                String url = configInfo.getFileServerHost();
                int port = Integer.parseInt(configInfo.getFileServerPort());
                String username = configInfo.getFileServerUsername();
                String password = configInfo.getFileServerPassword();
                FtpBusiness ftpBusiness = new FtpBusiness();
                FTPClient ftp = ftpBusiness.getConnectionFTP(url, port, username, password);
                ftpBusiness.uploadFile(ftp, filePath, fileName, in);
                ftpBusiness.closeFTP(ftp);
                log.info("*************************FtpUploadFileThread线程启动上传文件结束************************");
            } catch (RuntimeException e) {
                e.printStackTrace();
                log.info("*************************FtpUploadFileThread上传文件至ftp失败************************");
            }

        }
    }
}
